/*
 * Copyright 2007 Jeffrey Palm
 */

import java.io.*;
import javax.swing.*;

final class IPod {

  public File getCalendars() {
    return getSubdir("Calendars");
  }

  public File getContacts() {
    return getSubdir("Contacts");
  }

  public File getPhotos() {
    return getSubdir("Photos");
  }

  public File getNotes() {
    return getSubdir("Notes");
  }

  public File getIPodControl() {
    return getSubdir("iPod_Control");
  }

  public boolean importTrack(Track t) {
    return false;
  }

  private File getSubdir(String dir) {
    File r = null;
    do {
      r = getRoot();
      if (r == null) JOptionPane.showMessageDialog(null,"Please plug in your IPod","Error",JOptionPane.ERROR_MESSAGE);
    } while (r == null);
    return new File(r,dir);
  }

  private File root;
  public File getRoot() {
    if (root == null) root = findRoot();
    return root;
  }

  private File findRoot() {
    if (OS.isWindows()) {
      for (char c='E'; c<='Z'; c++) {
				File dir = new File(c + ":\\");
        if (isIpodDir(dir)) return dir;
      }
			for (char c='D'; c>='A'; c--) {
				File dir = new File(c + ":\\");
				if (isIpodDir(dir)) return dir;
      }
    } else if (OS.isMac()) {
			File volumesDir = new File("/Volumes");
			File[] vs = volumesDir.listFiles();
			if (vs != null) {
				for (int i=0; i<vs.length; i++) {
					File v = vs[i];
					if (isIpodDir(v)) return v;
				}
			}
		} else {
			//nothing now
		}
		return null;
  }

  private boolean isIpodDir(File dir) {
    if (dir == null) return false;
    if (!dir.isDirectory()) return false;
    if (!isDirectory(dir,"iPod_Control")) return false;
    if (!isDirectory(dir,"Notes")) return false;
    return true;
  }

  private boolean isDirectory(File dir,String dirName) {
    File f = new File(dir,dirName);
    if (!f.exists()) return false;
    if (!f.isDirectory()) return false;
    return true;
  }

  public String toString() {
    String res = "";
    res += "root   : " + getRoot()  + "\n";
    res += "notes  : " + getNotes() + "\n";
    return res;
  }

}